package com.ssl.security.util;

import org.apache.commons.codec.binary.Base64;

import com.ssl.security.constants.KeyFactoryAlgEnum;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * 描述：私钥工具类
 *
 * @author ssl
 * @create 2021/3/19 0019.
 */
public class PrivateKeyUtils {
    /**
     * 获取RSA私钥对象
     *
     * @param privateKeyBase64 私钥Base64
     * @return
     * @throws SecurityException
     */
    public static PrivateKey loadRSAPrivateKey(String privateKeyBase64) throws Exception {
        return loadPrivateKey(privateKeyBase64, KeyFactoryAlgEnum.RSA.getValue());
    }

    /**
     * 获取私钥对象
     *
     * @param privateKeyBase64
     * @param algorithm
     * @return
     * @throws Exception
     */
    public static PrivateKey loadPrivateKey(String privateKeyBase64, String algorithm) throws Exception {
        byte[] privateKeyByte = Base64.decodeBase64(privateKeyBase64);
        return loadPrivateKey(privateKeyByte, algorithm);
    }

    /**
     * 获取私钥对象
     *
     * @param encoded 私钥二进制流
     * @return
     * @throws SecurityException
     */
    public static PrivateKey loadPrivateKey(byte[] encoded, String algorithm) throws Exception {
        PrivateKey privateKey;
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory keyFactory = KeyFactoryUtils.getKeyFactory(algorithm);
        privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }
}
